package com.nba.system.interceptor;

import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.nba.common.cache.GlobalCache;
import com.nba.common.dao.IJdbcDao;
import com.nba.common.exception.CustomException;
import com.nba.common.framework.ErrorCode;
import com.nba.common.framework.UserSessionData;
import com.nba.common.utils.Environment;
import com.nba.common.utils.MapUtils;
import com.nba.system.cache.UserPrivCache;


/**
 * @author Jesse
 * 登录拦截器
 */
public class CheckLoginInterceptor implements HandlerInterceptor {
	@Autowired
	protected IJdbcDao jdbcDao;
	private static Logger logger = Logger.getLogger(CheckLoginInterceptor.class);
	
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
		//实现如下:
		//System.out.println("ControllerInterceptor.afterCompletion()");
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2, ModelAndView arg3) throws Exception {
		//实现如下:
		//System.out.println("ControllerInterceptor.postHandle()");
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		//实现如下:
		//System.out.println("ControllerInterceptor.preHandle()");
		String reqUrl = request.getServletPath();  
		logger.debug("request url================="+reqUrl);
		HttpSession session = request.getSession();
		//String path = request.getContextPath();
		//String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/login.jsp?err=2";
		
		UserSessionData usb = (UserSessionData) session.getAttribute(Environment.SESSION_USER_LOGIN_INFO);
		if(usb == null) {
			//判断是否有存cookie
			boolean hascookie = false;
			Cookie[] cookies = request.getCookies();
			if(cookies==null){
				throw new CustomException(ErrorCode.NO_SESSION);
				//response.sendRedirect(basePath);
				//return false;
			}
			for(Cookie cookie : cookies) {
				if((Environment.COOKIES_USER_NAME).equals(cookie.getName())) {//自动登录
					String usercode = cookie.getValue();
					usercode = new String(org.apache.commons.codec.binary.Base64.decodeBase64(java.net.URLDecoder.decode(usercode, "UTF-8")),"UTF-8");
					String loginsql = "select * from sys_user a where lower(a.USER_CODE)=lower(?)";
					Map<String, Object> map = jdbcDao.queryForMap(loginsql, new Object[]{usercode}); 
					if(map == null || map.size() == 0) {//login faiule
						throw new CustomException(ErrorCode.NAME_OR_PSW_ERROR);
						//response.sendRedirect(basePath);
						//return false;//登录失败，用户名或密码有误，请重新输入！
					} else {
						//request.getSession().setAttribute(Environment.LOGIN_INFO, map);
						usb = new UserSessionData();
						usb.setUserCode(map.get("user_code").toString());
						usb.setUserId(map.get("user_id").toString());
						usb.setUserName(map.get("user_name").toString());
						usb.setDomainId(Integer.parseInt(map.get("domain_id").toString()));
						usb.setDeptId(Integer.parseInt(map.get("dept_id").toString()));
						
						Map<String,List<String>> userPrivMap = GlobalCache.getCache(UserPrivCache.class,Map.class);
			            List<String> privList = userPrivMap.get(MapUtils.getString(map, "user_id"));
			            String[] userPrivIds=new String[]{};
			            if(privList!=null){
			                userPrivIds=privList.toArray(new String[]{});
			            }
						usb.setUserPrivIds(userPrivIds);
						//设置登录信息
						request.getSession().setAttribute(Environment.SESSION_USER_LOGIN_INFO, usb);
						//记录登录日志
						//...
					}
					hascookie = true; 
				}
			}  
			if(!hascookie){
				throw new CustomException(ErrorCode.NO_SESSION);
			}
		}else{
			//String noPrivPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/login.jsp?err=3";
			String urlId = reqUrl.substring(reqUrl.lastIndexOf("/")+1, reqUrl.length());
			String[] userPrivIds = usb.getUserPrivIds();
			if(!Environment.ADMIN_USER_CODE.equals(usb.getUserCode())) {
				Map<String, Object> urlSqlMap = jdbcDao.queryForMap(
						"select * from sys_url t where t.url_id=?",
						new Object[] { urlId });
				if (urlSqlMap == null || urlSqlMap.size() == 0) {
					throw new CustomException(ErrorCode.NO_PRIV);
				}
				String privId = urlSqlMap.get("PRIV_ID").toString();
				
				if(privId.equals(Environment.LOGIN_NO_PRIV)){//权限为登陆后可操作
					return true;
				} else if(privId.equals(Environment.ADMIN_PRIV) ) {//admin专属
					throw new CustomException(ErrorCode.NO_PRIV);
					//response.sendRedirect(noPrivPath);
					//return false;
				} else if(privId.equals(Environment.INNER_USER_PRIV)){//内部员工专属
					if(!Environment.INNER_USER_TYPE.equals(usb.getUserType())){
						throw new CustomException(ErrorCode.NO_PRIV);
					}
				} else {
					if(!this.hasPriv(userPrivIds, privId)){
						throw new CustomException(ErrorCode.NO_PRIV);
					}
				}
			}			
		}
		return true;
	}
	
	public boolean hasPriv(String[] privIds, String privId){
		if(privIds==null){
			return false;
		}
		for(String s: privIds){
			if(privId.equals(s)){
				return true;
			}
		}
		return false;
	}
}
